// 函数参数必须是字符串，因为二代身份证号码是十八位，而在javascript中，十八位的数值会超出计算范围，造成不精确的结果，导致最后两位和计算的值不一致，从而该函数出现错误。
// 详情查看javascript的数值范围
export const checkIDCard = function(idcode) {
    // 加权因子
    var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    // 校验码
    var check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

    var code = idcode + "";
    var last = idcode[17]; //最后一位

    var seventeen = code.substring(0, 17);

    // ISO 7064:1983.MOD 11-2
    // 判断最后一位校验码是否正确
    var arr = seventeen.split("");
    var len = arr.length;
    var num = 0;
    for (var i = 0; i < len; i++) {
        num = num + arr[i] * weight_factor[i];
    }

    // 获取余数
    var resisue = num % 11;
    var last_no = check_code[resisue];

    // 格式的正则
    // 正则思路
    /*
    第一位不可能是0
    第二位到第六位可以是0-9
    第七位到第十位是年份，所以七八位为19或者20
    十一位和十二位是月份，这两位是01-12之间的数值
    十三位和十四位是日期，是从01-31之间的数值
    十五，十六，十七都是数字0-9
    十八位可能是数字0-9，也可能是X
    */
    var idcard_patter =
        /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

    // 判断格式是否正确
    var format = idcard_patter.test(idcode);

    // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
    return last === last_no && format ? true : false;
}

//返回变量类型
export const gettype = function(data) {
    var pro = Object.prototype.toString;
    return pro.call(data);
}

export const checkPermission = async function(permisionID) {
    let result = "";
    let p = permisionID;
    // #ifdef APP-PLUS
    if (plus.os.name == "iOS") {
        if (permisionID == 'saveImage') p = 'photoLibrary';
        result = permission.judgeIosPermission(p);
    } else {
        switch (permisionID) {
            case 'location':
                p = 'android.permission.ACCESS_FINE_LOCATION';
                break;
            case 'photoLibrary':
                p = 'android.permission.READ_EXTERNAL_STORAGE';
                break;
            case 'saveImage':
                p = 'android.permission.WRITE_EXTERNAL_STORAGE';
                break;
            case 'camera':
                p = 'android.permission.CAMERA';
                break;
            default:
                break;
        }
        result = await permission.requestAndroidPermission(p) === -1 ? false : true;
    }
    // #endif
    // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
    result = await getSetting() === -1 ? false : true;

    function getSetting() {
        return new Promise((resolve, reject) => {
            uni.getSetting({
                success: res => {
                    switch (permisionID) {
                        case 'location':
                            p = 'userLocation';
                            break;
                        case 'photoLibrary':
                            p = 'writePhotosAlbum';
                            break;
                        case 'saveImage':
                            p = 'writePhotosAlbum';
                            break;
                        case 'camera':
                            p = 'camera';
                            break;
                        default:
                            break;
                    }
                    if (res.authSetting[`scope.${p}`] === undefined) {
                        resolve(0);
                        return;
                    }
                    if (res.authSetting[`scope.${p}`]) {
                        resolve(1)
                    } else {
                        resolve(-1);
                    }

                },
                fail: () => {

                }
            })
        })
    }
    // #endif
    if (!result) {
        let t = "";
        switch (permisionID) {
            case 'location':
                t = '您没有定位权限，请前往系统设置中开启';
                break;
            case 'photoLibrary':
                t = '您没有照片访问权限，请前往系统设置中开启';
                break;
            case 'saveImage':
                t = '您没有照片访问权限，请前往系统设置中开启';
                break;
            case 'camera':
                t = '您没有相机访问权限，请前往系统设置中开启';
                break;
            default:
                break;
        }
        uni.showModal({
            content: t,
            confirmColor: '#13D1BE',
            confirmText: '去设置',
            success: function(res) {
                if (res.confirm) {
                    // #ifdef APP-PLUS
                    permission.gotoAppPermissionSetting()
                    // #endif
                    // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
                    uni.openSetting({
                        success() {}
                    })
                    // #endif

                }
            }
        });
    }
    return result;
}

//保存图片到相册
export const saveImg = async function(url) {
    let result = await checkPermission('saveImage');
    return new Promise((resolve, reject) => {
        if (!url) return;
        if (!result) return;
        uni.saveImageToPhotosAlbum({ //........回调地狱
            filePath: url,
            success(res) {
                uni.showModal({
                    title: '提示',
                    content: '保存成功，请到相册查看',
                    showCancel: false,
                    confirmColor: '#0DE5CE'
                })
                resolve(res);
            },
            fail(error) {
                uni.downloadFile({
                    url: url,
                    success(res) {
                        if (res.statusCode === 200) {
                            uni.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success(res) {
                                    uni.showModal({
                                        title: '提示',
                                        content: '保存成功，请到相册查看',
                                        showCancel: false,
                                        confirmColor: '#0DE5CE'
                                    })
                                    resolve(res);
                                },
                                fail(error) {
                                    reject(error)
                                },
                                complete() {
                                    uni.hideLoading();
                                }
                            })
                        } else {
                            uni.showModal({
                                content: '您没有照片访问权限，请前往系统设置中开启',
                                confirmColor: '#13D1BE',
                                confirmText: '去设置',
                                success: function(res) {
                                    if (res.confirm) {
                                        // #ifdef APP-PLUS
                                        permission.gotoAppPermissionSetting()
                                        // #endif
                                        // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
                                        uni.openSetting({
                                            success() {}
                                        })
                                        // #endif

                                    }
                                }
                            });
                            reject(res)
                        }
                    },
                    fail(res) {
                        uni.saveImageToPhotosAlbum({
                            filePath: url,
                            success(res) {
                                uni.showModal({
                                    title: '提示',
                                    content: '保存成功，请到相册查看',
                                    showCancel: false,
                                    confirmColor: '#0DE5CE'
                                })
                                resolve(res);
                            },
                            fail(error) {
                                uni.showModal({
                                    content: res.errMsg
                                })
                                reject(error)
                            },
                            complete() {
                                uni.hideLoading();
                            }
                        })
                    }
                })
            },
            complete() {
                // console.log('下载失败',JSON.stringify(res))
                uni.hideLoading();
            }
        })
    })
}

/* 
 * 获取url字符串参数
 */
export const getRequestParameters = function(locationhref) {
    let href = locationhref || "";
    let theRequest = new Object();
    let str = href.split("?")[1];
    if (str != undefined) {
        let strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

// 日期格式化方法
export const dateFmt = function(td, fmtExp) {
    if (!td) {
        return ''
    }
    if (typeof td === 'string' && td.indexOf('-') !== -1) {
        td = td.replace(/-/g, '/')
    }
    const date = new Date(td)
    const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds() // 毫秒
    }
    let dateFmt = fmtExp
    if (/(y+)/.test(dateFmt)) {
        dateFmt = dateFmt.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length))
    }
    for (const k in o) {
        if (new RegExp(`(${k})`).test(dateFmt)) {
            dateFmt = dateFmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((`00${o[k]}`).substr((
                `${o[k]}`).length)))
        }
    }
    return dateFmt
}

/* 
 * 时间戳转时间返回单独分开的对象
 * Y-m-d H:i:s
 * 不传format将输出{y: 2019, m: "05", d: "29", h: "06", i: "42", …}
 */
export const format = function(timestamp, format) {
    var a, jsdate = ((timestamp) ? new Date(timestamp * 1000) : new Date());
    var pad = function(n, c) {
        if ((n = n + "").length < c) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    var txt_ordin = {
        1: "st",
        2: "nd",
        3: "rd",
        21: "st",
        22: "nd",
        23: "rd",
        31: "st"
    };
    var txt_months = ["", "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月",
        "十月", "十一月", "十二月"
    ];
    var f = {
        // Day 
        d: function() {
            return pad(f.j(), 2)
        },
        d1: function() {
            return pad(f.j(), 1)
        },
        D: function() {
            return f.l().substr(0, 3)
        },
        j: function() {
            return jsdate.getDate()
        },
        l: function() {
            return txt_weekdays[f.w()]
        },
        N: function() {
            return f.w() + 1
        },
        S: function() {
            return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'
        },
        w: function() {
            return jsdate.getDay()
        },
        z: function() {
            return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0
        },

        // Week 
        W: function() {
            var a = f.z(),
                b = 364 + f.L() - a;
            var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
            if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b) {
                return 1;
            } else {
                if (a <= 2 && nd >= 4 && a >= (6 - nd)) {
                    nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                    return date("W", Math.round(nd2.getTime() / 1000));
                } else {
                    return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                }
            }
        },

        // Month 
        F: function() {
            return txt_months[f.n()]
        },
        m: function() {
            return pad(f.n(), 2)
        },
        m1: function() {
            return pad(f.n(), 1)
        },
        M: function() {
            return f.F().substr(0, 3)
        },
        n: function() {
            return jsdate.getMonth() + 1
        },
        t: function() {
            var n;
            if ((n = jsdate.getMonth() + 1) == 2) {
                return 28 + f.L();
            } else {
                if (n & 1 && n < 8 || !(n & 1) && n > 7) {
                    return 31;
                } else {
                    return 30;
                }
            }
        },

        // Year 
        L: function() {
            var y = f.Y();
            return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0
        },
        //o not supported yet 
        Y: function() {
            return jsdate.getFullYear()
        },
        y: function() {
            return (jsdate.getFullYear() + "").slice(2)
        },

        // Time 
        a: function() {
            return jsdate.getHours() > 11 ? "pm" : "am"
        },
        A: function() {
            return f.a().toUpperCase()
        },
        B: function() {
            // peter paul koch: 
            var off = (jsdate.getTimezoneOffset() + 60) * 60;
            var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() +
                off;
            var beat = Math.floor(theSeconds / 86.4);
            if (beat > 1000) beat -= 1000;
            if (beat < 0) beat += 1000;
            if ((String(beat)).length == 1) beat = "00" + beat;
            if ((String(beat)).length == 2) beat = "0" + beat;
            return beat;
        },
        g: function() {
            return jsdate.getHours() % 12 || 12
        },
        G: function() {
            return jsdate.getHours()
        },
        h: function() {
            return pad(f.g(), 2)
        },
        H: function() {
            return pad(jsdate.getHours(), 2)
        },
        i: function() {
            return pad(jsdate.getMinutes(), 2)
        },
        s: function() {
            return pad(jsdate.getSeconds(), 2)
        },
        //u not supported yet 

        // Timezone 
        //e not supported yet 
        //I not supported yet 
        O: function() {
            var t = pad(Math.abs(jsdate.getTimezoneOffset() / 60 * 100), 4);
            if (jsdate.getTimezoneOffset() > 0) t = "-" + t;
            else t = "+" + t;
            return t;
        },
        P: function() {
            var O = f.O();
            return (O.substr(0, 3) + ":" + O.substr(3, 2))
        },
        //T not supported yet 
        //Z not supported yet 

        // Full Date/Time 
        c: function() {
            return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()
        },
        //r not supported yet 
        U: function() {
            return Math.round(jsdate.getTime() / 1000)
        }
    };
    if (!format) {
        return {
            y: f.Y(),
            m: f.m(),
            d: f.d(),
            h: f.h(),
            i: f.i(),
            s: f.s(),
            H: f.H(),
            l: f.l(),
            F: f.F(),
            m1: f.m1(),
            d1: f.d1()
        }
    }
    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s) {
        let ret;
        if (t != s) {
            // escaped 
            ret = s;
        } else if (f[s]) {
            // a date function exists 
            ret = f[s]();
        } else {
            // nothing special 
            ret = s;
        }
        return ret;
    });
}
/*
 *解析剩余时间
 */
export const returntime = function(value) { // 解析剩余时间
    let data = {}
    if (value >= 0) {
        let S = (value % 60) > 9 ? (value % 60) : '0' + (value % 60) // 秒
        let M = parseInt(value / 60 % 60) > 9 ? parseInt(value / 60 % 60) : '0' + parseInt(value / 60 % 60) // 分
        let H = parseInt(value / 60 / 60 % 24) > 9 ? parseInt(value / 60 / 60 % 24) : '0' + parseInt(value / 60 /
            60 % 24) // 时
        let T = parseInt(value / 60 / 60 / 24) > 9 ? parseInt(value / 60 / 60 / 24) : '0' + parseInt(value / 60 /
            60 / 24) // 天
        data = {
            s: S,
            m: M,
            h: H,
            t: T,
        }
    } else {
        data = {
            s: '00',
            m: '00',
            h: '00',
            t: '00',
        }
    }
    return data
};
